<template>
  <div class="app-container">
    <el-card>
      <el-form ref="contestForm" :model="contestForm" :rules="rules" label-width="100px">
        <el-form-item label="竞赛标题" prop="title">
          <el-input v-model="contestForm.title" />
        </el-form-item>
        <el-form-item label="题目编号" prop="problemIds">
          <el-input v-model="contestForm.problemIds" placeholder="例如：1001,1002,1003" />
        </el-form-item>
        <el-form-item label="开始时间" required>
          <el-row style="width: 480px">
            <el-col :span="11">
              <el-form-item prop="startDate">
                <el-date-picker v-model="contestForm.startDate" placeholder="选择日期" value-format="yyyy-MM-dd" />
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-form-item prop="startTime">
                <el-time-picker v-model="contestForm.startTime" placeholder="选择时间" value-format="HH:mm:ss" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="结束时间" required>
          <el-row style="width: 480px">
            <el-col :span="11">
              <el-form-item prop="endDate">
                <el-date-picker v-model="contestForm.endDate" placeholder="选择日期" value-format="yyyy-MM-dd" />
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-form-item prop="endTime">
                <el-time-picker v-model="contestForm.endTime" placeholder="选择时间" value-format="HH:mm:ss" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="竞赛描述" prop="description">
          <mavon-editor
            ref="desc"
            v-model="contestForm.description"
            :image-filter="uploadBefore"
            @imgAdd="addImage"
            @imgDel="delImage"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="禁用" prop="defunct">
              <el-switch v-model="contestForm.defunct" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="语言列表" prop="languages">
              <el-select
                v-model="contestForm.languages"
                multiple
                placeholder="请选择语言"
              >
                <el-option
                  v-for="item in languageOptions"
                  :key="item.num"
                  :label="item.label"
                  :value="item.num"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="权限" prop="privilege">
          <el-radio-group v-model="contestForm.privilege" @change="changePrivilege">
            <el-radio label="0">公开</el-radio>
            <el-radio label="1">私有</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="contestForm.privilege==='1'">
          <el-form-item label="密码">
            <el-input v-model="contestForm.password" maxlength="20">密码</el-input>
          </el-form-item>
          <el-form-item label="学生列表" prop="numbers">
            <el-input v-model="contestForm.numbers" type="textarea" :placeholder="numbersTips" :autosize="{minRows:5,maxRows:5}" />
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" @click="submitForm('contestForm')">立即保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { languageOptions } from '@/utils/global'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { addProblemImage, deleteProblemImage } from '@/api/problem'
import { Message } from 'element-ui'
import { getUserId } from '@/utils/auth'
import { addContest, contestAdminById } from '@/api/contest'

export default {
  components: { mavonEditor },
  data() {
    return {
      numbersTips: '38381717001\n38381717002\n38381717003\n*让学生在个人中心设置自己的学号，然后将学生学号从Excel粘贴到这里',
      languageOptions: languageOptions,
      contestId: -1,
      contestForm: {
        title: '',
        problemIds: '',
        startDate: '',
        startTime: '',
        endDate: '',
        endTime: '',
        password: '',
        defunct: false,
        languages: [],
        privilege: '0',
        description: '',
        numbers: null
      },
      rules: {
        title: [{ required: true, message: '请输入竞赛标题', trigger: 'blur' }],
        problemIds: [
          { required: true, message: '请输入题目集合', trigger: 'blur' },
          { pattern: '^\\d+(,\\d+)*$', message: '请合理输入', trigger: 'blur' }
        ],
        startDate: [{ type: 'string', required: true, message: '请选择日期', trigger: 'change' }],
        startTime: [{ type: 'string', required: true, message: '请选择时间', trigger: 'change' }],
        endDate: [{ type: 'string', required: true, message: '请选择日期', trigger: 'change' }],
        endTime: [{ type: 'string', required: true, message: '请选择时间', trigger: 'change' }],
        privilege: [{ required: true, message: '请选择权限', trigger: 'change' }],
        languages: [{ type: 'array', required: true, message: '请选择语言列表', trigger: 'change' }],
        description: [{ required: true, message: '请填写竞赛描述', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    if (this.$route.query.contestId !== undefined) {
      this.contestId = this.$route.query.contestId
      this.contestAdminById()
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.contestForm.privilege === '1' && this.contestForm.password.trim().length < 1) {
            this.$message.warning('请输入密码')
            return false
          }
          const formData = new FormData()
          formData.set('userId', getUserId())
          formData.set('title', this.contestForm.title)
          formData.set('problemIds', this.contestForm.problemIds)
          formData.set('startDateTime', this.contestForm.startDate + ' ' + this.contestForm.startTime)
          formData.set('endDateTime', this.contestForm.endDate + ' ' + this.contestForm.endTime)
          formData.set('defunct', this.contestForm.defunct)
          formData.set('languages', this.contestForm.languages)
          formData.set('privilege', this.contestForm.privilege)
          formData.set('description', this.contestForm.description)
          formData.set('numbers', this.contestForm.numbers || '')
          formData.set('password', this.contestForm.password)
          if (this.contestId !== -1) {
            formData.set('contestId', this.contestId)
          }
          addContest(formData).then(res => {
            if (res) {
              this.$message.success(res.message)
              if (this.contestId !== -1) {
                this.contestAdminById()
              }
            }
          }).catch(() => {
            if (this.contestId !== -1) {
              this.contestAdminById()
            }
          })
        }
      })
    },
    contestAdminById() {
      contestAdminById({ contestId: this.contestId }).then(res => {
        this.contestForm.startDate = res.data.startDateTime.split(' ')[0]
        this.contestForm.startTime = res.data.startDateTime.split(' ')[1]
        this.contestForm.endDate = res.data.endDateTime.split(' ')[0]
        this.contestForm.endTime = res.data.endDateTime.split(' ')[1]
        this.contestForm.defunct = res.data.defunct !== 'N'
        this.contestForm.title = res.data.title
        this.contestForm.problemIds = res.data.problemIds
        this.contestForm.description = res.data.description
        this.contestForm.privilege = String(res.data.privilege)
        this.contestForm.password = res.data.password
        this.contestForm.numbers = res.data.numbers || ''
        const language = res.data.language
        this.contestForm.languages = []
        let i = 0
        while (i < 10) {
          if (((1 << i) & language) !== 0) {
            this.contestForm.languages.push(i)
          }
          i++
        }
      })
    },
    changePrivilege() {
      if (this.contestForm.privilege === '0') {
        this.contestForm.password = ''
        this.contestForm.numbers = ''
      }
    },
    addImage(pos, file) {
      const formData = new FormData()
      formData.append('image', file)
      addProblemImage(formData).then(res => {
        this.$refs['desc'].$img2Url(pos, res.data)
      })
    },
    delImage(pos) {
      deleteProblemImage({ url: pos[0] }).then(res => {
        if (res.data) {
          Message.success({ showClose: true, message: '图片已删除' })
        }
      })
    },
    uploadBefore(file) {
      const af = file.name.split('.')[1]
      if (af !== 'jpg' && af !== 'jpeg' && af !== 'png' && af !== 'gif') {
        Message.error({ showClose: true, message: '图片格式限制为jpg,jpeg,png' })
        return false
      }
      if (file.size >= 20097152) {
        Message.error({ showClose: true, message: '图片最大为2M' })
        return false
      }
      return true
    }
  }
}
</script>

<style scoped>

</style>
